<template>
	<view class="container">
		<u-navbar title="搜索" :autoBack="true" fixed placeholder />
		<!-- 搜索头部 -->
		<view class="search-header">
			<view class="search-box">
				<u-icon name="search" size="40rpx" color="#999"></u-icon>
				<input class="search-input" v-model="keyword" placeholder="搜索你想听的节目" confirm-type="search" @confirm="onSearch" @input="onInput" focus />
				<u-icon v-if="keyword" name="close" size="40rpx" color="#999" @click="clearKeyword"></u-icon>
			</view>
			<text class="cancel-btn" @click="goBack">取消</text>
		</view>

		<!-- 搜索内容区 -->
		<view class="search-content">
			<!-- 搜索历史 -->
			<view class="search-history" v-if="!keyword && searchHistory.length">
				<view class="section-header">
					<text class="title">搜索历史</text>
					<u-icon name="trash" size="40rpx" color="#999" @click="clearHistory"></u-icon>
				</view>
				<view class="history-list">
					<view class="history-item" v-for="(item, index) in searchHistory" :key="index" @click="onHistoryClick(item)">
						<u-icon name="clock" size="32rpx" color="#999"></u-icon>
						<text class="history-text">{{ item }}</text>
					</view>
				</view>
			</view>

			<!-- 推荐搜索 -->
			<!-- <view class="recommend-search" v-if="!keyword">
        <view class="section-header">
          <text class="title">推荐搜索</text>
        </view>
        <view class="recommend-list">
          <view
            class="recommend-item"
            v-for="(item, index) in recommendList"
            :key="index"
            @click="onRecommendClick(item)"
          >
            <image
              class="recommend-image"
              :src="item.coverUrl"
              mode="aspectFill"
            />
            <view class="recommend-info">
              <text class="recommend-name">{{ item.name }}</text>
              <text class="recommend-desc">{{ item.description }}</text>
            </view>
          </view>
        </view>
      </view> -->

			<!-- 热门搜索 -->
			<view class="hot-search" v-if="!keyword">
				<view class="section-header">
					<text class="title">热门搜索</text>
				</view>
				<view class="hot-list">
					<view class="hot-item" v-for="(item, index) in hotSearchList" :key="index" @click="onHotClick(item)">
						<text class="hot-rank" :class="{ 'top-three': index < 3 }">{{ index + 1 }}</text>
						<text class="hot-text">{{ item.name }}</text>
						<text class="hot-tag" v-if="item.isHot">HOT</text>
					</view>
				</view>
			</view>

			<!-- 搜索建议 -->
			<!-- <view class="search-suggest" v-if="keyword && suggestList.length">
        <view
          class="suggest-item"
          v-for="(item, index) in suggestList"
          :key="index"
          @click="onSuggestClick(item)"
        >
          <u-icon name="search" size="32rpx" color="#999"></u-icon>
          <text class="suggest-text">{{ item }}</text>
        </view>
      </view> -->

			<!-- 搜索结果 -->
			<view class="search-result" v-if="keyword && isSearched">
				<!-- <view class="result-tabs">
          <view
            class="tab-item"
            v-for="(tab, index) in resultTabs"
            :key="index"
            :class="{ active: currentTab === index }"
            @click="switchTab(index)"
          >
            {{ tab.name }}
          </view>
        </view> -->
				<view class="result-list">
					<view class="result-item" v-for="(item, index) in currentResults" :key="index" @click="goDetail(item)">
						<view class="result-image">
							<u-image :src="item.cover_url" width="120rpx" height="120rpx" radius="12rpx" mode="aspectFill" />
						</view>
						<view class="result-info">
							<text class="result-name">{{ item.title.split(' by ')[0].trim() }}</text>
							<text class="result-desc u-line-1">{{ item.description }}</text>
							<view class="result-meta">
								<view class="play-count">
									<u-icon name="play-right-fill" size="24rpx" color="#999" />
									{{ formatViewCount(item.views) }}
								</view>
							</view>
						</view>
					</view>

					<!-- <recommend-list :list="currentResults" @detail="goDetail" /> -->
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { formatViewCount } from '../../utils/format.js';
import RecommendList from '../../components/recommend-list.vue';

export default {
	components: {
		RecommendList
	},
	data() {
		return {
			keyword: '',
			isSearched: false,
			currentTab: 0,
			searchHistory: [],
			hotSearchList: [],
			suggestList: [],
			resultTabs: [],
			searchResults: {
				all: [],
				album: [],
				audio: [],
				user: []
			},
			recommendList: [],
			currentResults: [],
			page: 1
		};
	},

	// computed: {
	// 	currentResults() {
	// 		const type = this.resultTabs[this.currentTab].type;
	// 		return this.searchResults[type];
	// 	}
	// },

	created() {
		// 获取本地存储的搜索历史
		const history = uni.getStorageSync('searchHistory');
		if (history) {
			this.searchHistory = JSON.parse(history);
		}
	},
	onShow() {
		this.getHotList();
	},
	onReachBottom() {
		this.page++;
		this.getHotList();
	},
	methods: {
		formatViewCount,
		getHotList() {
			let PostData = {
				ac: 'gethome'
			};
			uni.$u.http.post('', PostData).then((res) => {
				let newList = res.tuijian.map((item) => {
					let title = item.title.split(' by ')[0].trim();
					return {
						id: item.id,
						name: title,
						description: item.description,
						coverUrl: item.cover_url,
						viewCount: item.views
					};
				});
				this.hotSearchList = [...this.hotSearchList, ...newList];
			});
		},

		goBack() {
			uni.navigateBack();
		},

		clearKeyword() {
			this.keyword = '';
			this.isSearched = false;
			this.page = 1;
		},

		onInput() {
			// 模拟搜索建议
			if (this.keyword) {
				this.suggestList = [this.keyword + '相关内容1', this.keyword + '相关内容2', this.keyword + '相关内容3'];
			} else {
				this.suggestList = [];
			}
		},

		onSearch() {
			if (!this.keyword.trim()) return;

			this.isSearched = true;
			this.saveSearchHistory(this.keyword);
			let PostData = {
				ac: 'sreach',
				keyword: this.keyword,
				page: 1
			};
			uni.$u.http.post('', PostData).then((res) => {
				console.log('搜索结果', res);
				this.currentResults = res;
			});
			// this.mockSearchResults();
		},

		onHistoryClick(keyword) {
			this.keyword = keyword;
			this.onSearch();
		},

		onHotClick(item) {
			this.keyword = item.name;
			this.onSearch();
		},

		onSuggestClick(keyword) {
			this.keyword = keyword;
			this.onSearch();
		},

		saveSearchHistory(keyword) {
			const index = this.searchHistory.indexOf(keyword);
			if (index > -1) {
				this.searchHistory.splice(index, 1);
			}
			this.searchHistory.unshift(keyword);
			if (this.searchHistory.length > 10) {
				this.searchHistory.pop();
			}
			uni.setStorageSync('searchHistory', JSON.stringify(this.searchHistory));
		},

		clearHistory() {
			this.searchHistory = [];
			uni.removeStorageSync('searchHistory');
		},

		switchTab(index) {
			this.currentTab = index;
		},

		goDetail(item) {
			uni.navigateTo({
				url: `/pages/album/detail?id=${item.id}`
			});
		},

		// 模拟搜索结果
		mockSearchResults() {
			this.searchResults = {
				all: [
					{
						id: 1,
						name: '冥想引导：专注力训练',
						description: '每天10分钟，提升专注力和工作效率',
						coverUrl: 'https://ui-avatars.com/api/?name=冥想&background=2d4059&color=fff',
						viewCount: 1500000
					},
					{
						id: 2,
						name: '正念课程：压力管理',
						description: '学会调节情绪，缓解压力',
						coverUrl: 'https://ui-avatars.com/api/?name=正念&background=ea5455&color=fff',
						viewCount: 890000
					}
				],
				album: [
					{
						id: 3,
						name: '冥想音乐合集',
						description: '精选放松音乐，助你进入冥想状态',
						coverUrl: 'https://ui-avatars.com/api/?name=音乐&background=2d4059&color=fff',
						viewCount: 650000
					}
				],
				audio: [
					{
						id: 4,
						name: '10分钟呼吸练习',
						description: '快速平静心情的呼吸技巧',
						coverUrl: 'https://ui-avatars.com/api/?name=呼吸&background=ea5455&color=fff',
						viewCount: 320000
					}
				],
				user: [
					{
						id: 5,
						name: '正念导师小王',
						description: '专业正念冥想导师',
						coverUrl: 'https://ui-avatars.com/api/?name=导师&background=2d4059&color=fff',
						viewCount: 180000
					}
				]
			};
		},

		onRecommendClick(item) {
			this.keyword = item.name;
			this.onSearch();
		}
	}
};
</script>

<style lang="scss">
@mixin text-ellipsis {
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
}

.container {
	min-height: 100vh;
	background: #fff;
}

.search-header {
	display: flex;
	align-items: center;
	padding: 20rpx;
	background: #fff;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

	.search-box {
		flex: 1;
		height: 72rpx;
		background: #f5f5f5;
		border-radius: 36rpx;
		display: flex;
		align-items: center;
		padding: 0 20rpx;
		transition: all 0.3s;

		&:focus-within {
			background: #fff;
			box-shadow: 0 0 0 2rpx #ff4d4f20;
		}

		.u-icon {
			margin-right: 10rpx;
		}

		.search-input {
			flex: 1;
			height: 100%;
			font-size: 28rpx;
		}
	}

	.cancel-btn {
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #333;
		transition: opacity 0.2s;

		&:active {
			opacity: 0.7;
		}
	}
}

.search-content {
	padding: 20rpx;

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;

		.title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
	}
}

.search-history {
	margin-bottom: 40rpx;

	.history-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;

		.history-item {
			display: flex;
			align-items: center;
			padding: 10rpx 20rpx;
			background: #f5f5f5;
			border-radius: 30rpx;

			.u-icon {
				margin-right: 10rpx;
			}

			.history-text {
				font-size: 26rpx;
				color: #666;
			}
		}
	}
}

.hot-search {
	.hot-list {
		.hot-item {
			display: flex;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #f5f5f5;
			transition: background-color 0.2s;

			&:active {
				background-color: #f9f9f9;
			}

			.hot-rank {
				width: 40rpx;
				font-size: 32rpx;
				font-weight: bold;

				&.top-three {
					color: #ff4d4f;
					font-size: 36rpx;
				}
			}

			.hot-text {
				flex: 1;
				font-size: 28rpx;
				color: #333;
				margin: 0 20rpx;
			}

			.hot-tag {
				font-size: 20rpx;
				color: #ff4d4f;
				border: 1rpx solid currentColor;
				padding: 2rpx 8rpx;
				border-radius: 4rpx;
				background: rgba(255, 77, 79, 0.1);
			}
		}
	}
}

.search-suggest {
	.suggest-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f5f5f5;

		.u-icon {
			margin-right: 20rpx;
		}

		.suggest-text {
			font-size: 28rpx;
			color: #333;
		}
	}
}

.search-result {
	.result-tabs {
		display: flex;
		border-bottom: 1rpx solid #f5f5f5;
		margin-bottom: 20rpx;

		.tab-item {
			padding: 20rpx 40rpx;
			font-size: 28rpx;
			color: #666;
			position: relative;

			&.active {
				color: #333;
				font-weight: bold;

				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 40rpx;
					right: 40rpx;
					height: 4rpx;
					background: #ff4d4f;
					border-radius: 2rpx;
					transition: all 0.3s;
				}
			}
		}
	}

	.result-list {
		.result-item {
			display: flex;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #f5f5f5;
			transition: background-color 0.2s;

			&:active {
				background-color: #f9f9f9;
			}

			.result-image {
				// width: 120rpx;
				// height: 120rpx;
				// border-radius: 12rpx;
				margin-right: 20rpx;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
			}

			.result-info {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;

				.result-name {
					font-size: 28rpx;
					color: #333;
					font-weight: bold;
					@include text-ellipsis;
					max-width: 80%;
				}

				.result-desc {
					font-size: 24rpx;
					color: #999;
					// @include text-ellipsis;
					margin: 10rpx 0;
					max-width: 80%;
				}

				.result-meta {
					display: flex;
					align-items: center;

					.play-count {
						font-size: 24rpx;
						color: #999;
						display: flex;
						align-items: center;

						.u-icon {
							margin-right: 4rpx;
						}
					}
				}
			}
		}
	}
}

.recommend-search {
	margin-bottom: 40rpx;

	.recommend-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;

		.recommend-item {
			display: flex;
			align-items: center;
			padding: 10rpx 20rpx;
			background: #f5f5f5;
			border-radius: 30rpx;
			max-width: calc(100% - 40rpx);
			transition: background-color 0.2s;

			&:active {
				background-color: #eee;
			}

			.recommend-image {
				width: 32rpx;
				height: 32rpx;
				border-radius: 50%;
				margin-right: 10rpx;
			}

			.recommend-info {
				.recommend-name {
					font-size: 26rpx;
					color: #666;
					@include text-ellipsis;
				}

				.recommend-desc {
					display: none;
				}
			}
		}
	}
}
</style>
